import { login, getInfo, getInfoById } from '@/api/user.js'
import { getToken, setToken, removeToken, setTimeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {}
}

const mutations = {
  setToken(state, payLoad) {
    state.token = payLoad
    setToken(payLoad)
    setTimeToken()
  },
  setUserInfo(state, payLoad) {
    state.userInfo = payLoad
  },
  logout(state) {
    state.token = ''
    removeToken()
    resetRouter()
    console.log(router)
    state.userInfo = {}
  }
}

const actions = {
  async login(context, data) {
    const res = await login(data)
    context.commit('setToken', res)
  },
  async getUserInfo(context) {
    const res = await getInfo()
    // res.roles.points.forEach((item, index) => {
    //   res.roles.points[index] = item.toLocaleLowerCase()
    // })
    const userInfoRes = await getInfoById(res.userId)
    context.commit('setUserInfo', { ...res, ...userInfoRes })
    return res
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

